/**
 * Created by ZhaoJinBing on 2017/8/4.
 */
define(['jquery', 'layer', 'js/common/uuid', 'easyui_zh_CN', 'easyui'], function ($, layer, uuid) {
    var create = function (setting) {
        if (!$.isPlainObject(setting)) {
            $.error('setting 不能为空');
        }

        var formId = setting.id;
        if (!formId) {
            formId = uuid.uuid();
        }
        var url = setting.url;
        var method = setting.method ? setting.method : 'POST';
        var style = setting.style ? setting.style : 'margin-top: 15px';
        var inline = setting.inline;
        var appendTo = setting.appendTo ? setting.appendTo : 'body';

        var form = $('<form action="'+url+'" id="'+formId+'" method="'+method+'" style="'+style+'"></form>');
        form.appendTo(appendTo);
        var items = setting.items ? setting.items : [];
        var btns = setting.btns ? setting.btns : [];
        initFormFields(items, inline, form);
        initFormBtns(btns, inline, form, getFunArg(arguments));
        form.destroy = function () {
            destroyForm(form);
        };
        form.submit = function (option) {
            submitForm(form, option);
        };
        form.reset = function (option) {
            form.form('reset');
            var callback = option.callback;
            if (callback) {
                callback(form);
            }
        };
        return form;
    };

    var getFunArg = function (args) {
        var argFunArr = [];
        if (args.length > 1) {
            $.each(args, function (index, arg) {
                if ($.isFunction(arg)) {
                    argFunArr.push(arg);
                }
            })
        }
        return argFunArr;
    };

    var initFormFields = function (fields, inline, form) {
        var defaultFieldOption = {
            validateOnCreate: false,
            validateOnBlur: true,
            width: '100%'
        };
        $.each(fields, function (index, field) {
            var type = field.type;
            var id = field.id;
            if (!id) {
                id = uuid.uuid();
            }
            var name = field.name;
            var option = $.extend({}, defaultFieldOption, field.option);
            var divObj, jObj;
            if (inline == true) {
                divObj = $('<div style="float: left;margin:10px 30px 0 0;"></div>');
            } else {
                divObj = $('<div style="margin-top: 20px;"></div>');
            }
            if (type.indexOf('combo') == 0) {
                jObj = $('<select id="'+id+'" name="'+name+'"></select>');
            } else {
                jObj = $('<input id="'+id+'" name="'+name+'">');
            }
            jObj.appendTo(divObj);
            divObj.appendTo(form);
            switch (type) {
                case 'textbox':
                    jObj.textbox(option);
                    break;
                case 'passwordbox':
                    jObj.passwordbox(option);
                    break;
                case 'combo':
                    jObj.combo(option);
                    break;
                case 'combobox':
                    jObj.combobox(option);
                    break;
                case 'combotree':
                    jObj.combotree(option);
                    break;
                case 'combogrid':
                    jObj.combogrid(option);
                    break;
                case 'combotreegrid':
                    jObj.combotreegrid(option);
                    break;
                case 'tagbox':
                    jObj.tagbox(option);
                    break;
                case 'numberbox':
                    jObj.numberbox(option);
                    break;
                case 'datebox':
                    jObj.datebox(option);
                    break;
                case 'datetimebox':
                    jObj.datetimebox(option);
                    break;
                case 'datetimespinner':
                    jObj.datetimespinner(option);
                    break;
                case 'spinner':
                    jObj.spinner(option);
                    break;
                case 'numberspinner':
                    jObj.numberspinner(option);
                    break;
                case 'timespinner':
                    jObj.timespinner(option);
                    break;
                case 'slider':
                    jObj.slider(option);
                    break;
                case 'filebox':
                    jObj.slider(option);
                    break;
            }
        });
    };

    var initFormBtns = function (btns, inline, form, callbacks) {
        var btnDefaultMap = {
            'submit': {
                'text': '提交',
                'icon': 'icon-ok',
                'width': '80px',
                'fun': 'submit'
            },
            'reset': {
                'text': '重置',
                'icon': 'icon-reload',
                'width': '80px',
                'fun': 'reset'
            }
        };

        var btnDiv;
        if (inline == true) {
            btnDiv = $('<div style="float: left;margin:10px 15px 0 0"></div>');
        } else {
            btnDiv = $('<div style="text-align:center;margin-top: 15px"></div>');
        }
        btnDiv.appendTo(form);
        $.each(btns, function (index, btn) {
            var btnJObj = $('<a></a>').appendTo(btnDiv);
            $('<span>&nbsp;&nbsp;&nbsp;&nbsp;</span>').appendTo(btnDiv);

            if ($.type(btn) === 'string') {
                var btnSetting, key = null;

                $.each(btnDefaultMap, function (k) {
                    if (btn.indexOf(k) == 0) {
                        key = k;
                        return false;
                    }
                });
                if (!key) {
                    return true;
                }
                var params = btn.replace(key, '');
                var callback, text, icon, width;
                if (params && params.length > 0) {
                    var pArr = $.parseJSON(params);
                    text = pArr[0];
                    icon = pArr[1];
                    width = pArr[2];
                }
                if (!text) text = btnDefaultMap[key]['text'];
                if (!icon) icon = btnDefaultMap[key]['icon'];
                if (!width) width = btnDefaultMap[key]['width'];
                var defaultFun = btnDefaultMap[key]['fun'];
                var btnClickOpt = {};
                if (callbacks[index]) {
                    btnClickOpt['callback'] = function () {
                        callbacks[index](form);
                    }
                }
                var clickCallback;
                if (defaultFun) {
                    clickCallback = function () {
                        new Function('target', 'callback', 'target.' + defaultFun + '(callback)')(form, btnClickOpt);
                    };
                } else {
                    clickCallback = function () {
                        callbacks[index](form);
                    }
                }
                btnSetting = {
                    text: text,
                    width: width,
                    iconCls: icon,
                    onClick: clickCallback
                };
                btnJObj.linkbutton(btnSetting);
            } else {
                btnJObj.linkbutton(btn);
            }
        });
    };

    var submitForm = function (target, option) {
        if (target == undefined) {
            return;
        }
        var load = layer.load(2);
        var submitCallback, callback;
        if (option) {
            submitCallback = option['submitCallback'];
            callback = option.callback;
        }
        var defaultOption = {
            onSubmit: function () {
                var isValid = $(target).form('validate');
                if (!isValid) {
                    layer.close(load);
                }
                if (submitCallback) {
                    submitCallback();
                }
                return isValid;
            },
            success: function (res) {
                layer.close(load);
                var obj = $.parseJSON(res);
                if (obj.success) {
                    if (callback) {
                        callback(obj);
                    }
                } else {
                    layer.msg(obj.message, {timeout: 1000});
                }
            }
        };
        $(target).form('submit', $.extend({}, defaultOption, option));
    };

    var destroyForm = function (target) {
        $(target).remove();
    };

    return {
        create: create,
        destroy: destroyForm,
        submit: submitForm
    }
});